/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-07-23     Administrator       the first version
 */
#ifndef APPLICATIONS_IO_IO_H_
#define APPLICATIONS_IO_IO_H_
#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>

/////////////////////////////////////OUT/////////////////////////////////////
#define RELAY0_PIN                      GET_PIN(A,11)
#define RELAY1_PIN                      GET_PIN(B,15)
#define LED3_PIN                        GET_PIN(A,8)
/////////////////////////////////////IN//////////////////////////////////////
#define KEY0_STATUS                     0
#define KEY1_STATUS                     1
#define KEY2_STATUS                     2
#define KEY3_STATUS                     3

#define INFRARED_STATUS                 4
#define DOOR_STATUS                     5
#define RELAY0_STATUS                   6
#define RELAY1_STATUS                   7

#define ANYBODY_PIN_STATUS              1               //有人IO口状态，1：红外接NC(常闭，检测有人，断开上拉至高);0:反之

#define DOOR_OPEN_PIN_STATUS            1               //开门IO口状态，1：门禁接NO(常开，门开，断开上拉至高);0:反之

#define RELAY0                          RELAY0_PIN
#define RELAY1                          RELAY1_PIN

// #define RELAY_ON                        0
// #define RELAY_OFF                       1

#define PCF8574_ADDR                    (0X40>>1)
rt_uint8_t get_io_status(uint8_t IO_PIN);
void set_io_status(uint8_t relayx, uint8_t status);

// 状态表示
enum {
    DEV_INFRARED_ANYBODY = 1, // 红外有人
    DEV_INFRARED_NOBODY = 0,  // 红外无人

    DEV_DOOR_OPEN = 1,  // 门禁开启
    DEV_DOOR_CLOSE = 0, // 门禁关闭

    DEV_RELAY_ON = 0,  // 继电器开
    DEV_RELAY_OFF = 1, // 继电器关

    DEV_KEY_PRESS = 1,   // 按键按下
    DEV_KEY_RELEASE = 0, // 按键释放

    DEV_CHAIN_OK = 1,    // 连锁正常
    DEV_CHAIN_ERROR = 0, // 连锁异常
};

// 状态结构体
typedef struct io_status_s
{
    rt_uint8_t infrared;
    rt_uint8_t door;
    rt_uint8_t relay0;
    rt_uint8_t relay1;
    rt_uint8_t key0;
    rt_uint8_t key1;
    rt_uint8_t key2;
    rt_uint8_t key3;
    rt_uint8_t chain; // 连锁状态
} io_status_s;

#define INFRARED_NOBODY_TIMEOUT 10 // 无人超时时间，单位s
rt_uint8_t _nobody_timeout;
rt_uint8_t _nobody_flag;
rt_uint8_t _nobody_cnt;

// 回调函数
typedef void(*IO_UPLOAD_CALLBACK)(struct io_status_s *io_status);
IO_UPLOAD_CALLBACK io_upload_callback;

#define IO_CHECK_PERIOD 200 // io检查线程周期，单位ms

void io_check_start();
void io_check_once();

#endif /* APPLICATIONS_IO_IO_H_ */
